const COS = require('cos-nodejs-sdk-v5');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

/**
 * 腾讯云exe文件上传服务
 * 专门用于上传whistle-client的构建产物到腾讯云存储
 */
class COSUploader {
  constructor() {
    // 腾讯云COS配置 - 复用现有配置
    this.config = {
      SecretId: process.env.COS_SECRET_ID || 'AKIDvx7ERG4nOpV9h5LRM709KNJ9xtsjnwCK',
      SecretKey: process.env.COS_SECRET_KEY || '4z8A3oU2QirpdLuNgopgNtYbaVH6rW1S',
      Bucket: process.env.COS_BUCKET || 'baoqu-host-manager-1252921383',
      Region: process.env.COS_REGION || 'ap-guangzhou'
    };

    // 初始化COS客户端
    this.cos = new COS({
      SecretId: this.config.SecretId,
      SecretKey: this.config.SecretKey
    });

    // 云端存储路径配置
    this.releasesPath = 'releases/';
    this.maxVersions = 10; // 保留的最大版本数量
  }

  /**
   * 生成云端存储路径
   * @param {string} version 版本号
   * @returns {string} 云端路径
   */
  generateCloudPath(version) {
    const fileName = `whistle-client-v${version}.exe`;
    return path.join(this.releasesPath, fileName).replace(/\\/g, '/');
  }

  /**
   * 获取exe文件信息
   * @param {string} filePath 本地文件路径
   * @returns {Object} 文件信息
   */
  getExeFileInfo(filePath) {
    try {
      if (!fs.existsSync(filePath)) {
        return null;
      }

      const stats = fs.statSync(filePath);
      const fileName = path.basename(filePath);
      
      // 计算文件MD5
      const fileBuffer = fs.readFileSync(filePath);
      const md5Hash = crypto.createHash('md5').update(fileBuffer).digest('hex');

      return {
        fileName,
        filePath,
        fileSize: stats.size,
        lastModified: stats.mtime,
        md5: md5Hash
      };
    } catch (error) {
      console.error('获取文件信息失败:', error.message);
      return null;
    }
  }

  /**
   * 上传exe文件到腾讯云
   * @param {string} filePath 本地exe文件路径
   * @param {string} version 版本号
   * @returns {Promise<Object>} 上传结果
   */
  async uploadExeFile(filePath, version) {
    try {
      // 验证文件
      const fileInfo = this.getExeFileInfo(filePath);
      if (!fileInfo) {
        return {
          success: false,
          error: '文件不存在或无法读取'
        };
      }

      // 先删除所有旧版本
      console.log('🔄 开始清理旧版本...');
      await this.deleteAllOldVersions();
      console.log('✅ 旧版本清理完成');

      // 生成云端路径
      const cloudPath = this.generateCloudPath(version);
      
      // 读取文件内容
      const fileContent = fs.readFileSync(filePath);
      
      // 上传到腾讯云
      const result = await this.cos.putObject({
        Bucket: this.config.Bucket,
        Region: this.config.Region,
        Key: cloudPath,
        Body: fileContent,
        ContentType: 'application/octet-stream',
        Headers: {
          'x-cos-meta-version': version,
          'x-cos-meta-file-name': fileInfo.fileName,
          'x-cos-meta-file-size': fileInfo.fileSize.toString(),
          'x-cos-meta-md5': fileInfo.md5,
          'x-cos-meta-upload-time': new Date().toISOString(),
          'x-cos-meta-uploader': 'whistle-client-builder'
        }
      });

      console.log(`exe文件上传成功: ${cloudPath}`);
      console.log(`文件大小: ${(fileInfo.fileSize / 1024 / 1024).toFixed(2)} MB`);
      
      return {
        success: true,
        url: `https://${this.config.Bucket}.cos.${this.config.Region}.myqcloud.com/${cloudPath}`,
        cloudPath,
        fileInfo
      };
    } catch (error) {
      console.error('上传exe文件失败:', error.message);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 列出已上传的版本
   * @returns {Promise<Array>} 版本列表
   */
  async listUploadedVersions() {
    try {
      const result = await this.cos.getBucket({
        Bucket: this.config.Bucket,
        Region: this.config.Region,
        Prefix: this.releasesPath
      });
      
      if (!result.Contents) {
        return [];
      }

      return result.Contents
        .filter(item => item.Key.endsWith('.exe'))
        .map(item => {
          const fileName = path.basename(item.Key);
          const version = fileName.replace('whistle-client-v', '').replace('.exe', '');
          return {
            key: item.Key,
            fileName,
            version,
            size: item.Size,
            lastModified: item.LastModified
          };
        })
        .sort((a, b) => new Date(b.lastModified) - new Date(a.lastModified));
    } catch (error) {
      console.error('获取版本列表失败:', error.message);
      return [];
    }
  }

  /**
   * 删除旧版本，保留指定数量
   * @param {number} keepCount 保留的版本数量
   * @returns {Promise<number>} 删除的文件数量
   */
  async deleteOldVersions(keepCount = this.maxVersions) {
    try {
      const versions = await this.listUploadedVersions();
      
      if (versions.length <= keepCount) {
        return 0;
      }

      const toDelete = versions.slice(keepCount);
      let deletedCount = 0;

      for (const version of toDelete) {
        try {
          await this.cos.deleteObject({
            Bucket: this.config.Bucket,
            Region: this.config.Region,
            Key: version.key
          });
          console.log(`删除旧版本: ${version.fileName}`);
          deletedCount++;
        } catch (error) {
          console.error(`删除版本失败 ${version.fileName}:`, error.message);
        }
      }

      return deletedCount;
    } catch (error) {
      console.error('清理旧版本失败:', error.message);
      return 0;
    }
  }

  /**
   * 删除所有旧版本（保留最新版本）
   * @returns {Promise<number>} 删除的文件数量
   */
  async deleteAllOldVersions() {
    try {
      const versions = await this.listUploadedVersions();
      
      if (versions.length === 0) {
        console.log('没有找到需要删除的旧版本');
        return 0;
      }

      console.log(`找到 ${versions.length} 个旧版本，开始删除...`);
      let deletedCount = 0;

      for (const version of versions) {
        try {
          await this.cos.deleteObject({
            Bucket: this.config.Bucket,
            Region: this.config.Region,
            Key: version.key
          });
          console.log(`🗑️  删除旧版本: ${version.fileName}`);
          deletedCount++;
        } catch (error) {
          console.error(`❌ 删除版本失败 ${version.fileName}:`, error.message);
        }
      }

      console.log(`✅ 成功删除 ${deletedCount} 个旧版本`);
      return deletedCount;
    } catch (error) {
      console.error('❌ 删除所有旧版本失败:', error.message);
      return 0;
    }
  }

  /**
   * 检查文件是否已存在
   * @param {string} version 版本号
   * @returns {Promise<boolean>} 是否存在
   */
  async fileExists(version) {
    try {
      const cloudPath = this.generateCloudPath(version);
      
      await this.cos.headObject({
        Bucket: this.config.Bucket,
        Region: this.config.Region,
        Key: cloudPath
      });
      return true;
    } catch (error) {
      return false;
    }
  }

  /**
   * 获取上传进度（模拟）
   * @param {number} fileSize 文件大小
   * @param {number} uploadedSize 已上传大小
   * @returns {number} 上传进度百分比
   */
  getUploadProgress(fileSize, uploadedSize) {
    return Math.round((uploadedSize / fileSize) * 100);
  }
}

// 创建单例实例
const cosUploader = new COSUploader();

module.exports = cosUploader;
